#include<stdio.h>

#include<sys/types.h>
#include<unistd.h>
#include<wait.h>

int main(){
	pid_t pid = getpid();
	int i, status;

	for (i = 0; i < 5; i++){
		pid = fork();
		if (pid == -1) {
			printf("fork error!\n");
			waitpid(0, &status, 0);
			return -1;
		} else if (pid == 0) 
			break;
	}

	if (pid == 0){
		sleep(1);
		printf("child %d has over!\n", getpid());
		return 99;
	}else if (pid > 0 ){
		int status;
		printf("last pid is %d\n", pid);
		// pid = waitpid(pid, &status, 0);
		// pid字段
		// >0 等待对应的pid退出
		// -1 回收任意子进程
		// 0  回收当前组的所有子进程
		// <-1 回收指定组的任意子进程 
		waitpid(0, &status, 0);
		// WNOHANG 不阻塞运行
		// waitpid(pid, &status, WNOHANG);

		if(WIFEXITED(status)){
			printf("pid %d has over with status code %d\n", pid, WEXITSTATUS(status));
		}else{
			printf("pid %d has over!\n", pid);
		}
	}


	return 0;
}
